/**
 * 添加或者修改页面
 */
let labelTimesJson
var ContentArticleInfoDlg = {
    data: {
        id: "",
        title: "",
        author: "",
        areaId: "",
        identityLevelIds: "",
        meritoriousLevelIds: "",
        description: "",
        textContent: "",
        imageUrl: "",
        status: "",
        createTime: "",
        updateTime: "",
        createUser: "",
        deleteFlag: "",
        updateUser: "",
        originateId: ""
    }
};
labelTimes = [];
layui.use(['form', 'admin', 'ax', 'laydate', 'upload', 'xmSelect'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var xmSelect = layui.xmSelect;
    var upload = layui.upload;
    var laydate = layui.laydate;
    laydate.render({
        elem: '#articleTime'
        , type: 'datetime'
    });
    var upload = layui.upload;
    //表单提交事件
    form.on('submit(btnSubmit)', function (data) {
        let labelTimes = [];
        if (data.field && data.field.labelIds) {
            let errFlag = false
            $.each(data.field.labelIds.split(","), function (i, item) {
                let times = $("#label_" + item).val();
                if (times >= 10) {
                    Changein.error("匹配次数小于10！")
                    errFlag = true
                    return
                }
                let labelData = {id: item, times: times}
                labelTimes.push(labelData);
            })
            if (errFlag) {
                return false;
            }
        }
        data.field.labelTimes = JSON.stringify(labelTimes);
        var ajax = new $ax(Changein.ctxPath + "/contentArticle/addItem", function (data) {
            Changein.success("添加成功！");
            window.location.href = Changein.ctxPath + '/contentArticle'
        }, function (data) {
            Changein.error("添加失败！" + data.responseJSON.message)
        });
        ajax.set(data.field);
        ajax.start();

        return false;
    });

    $('#cancel').click(function () {
        window.location.href = Changein.ctxPath + '/contentArticle'
    });
    //选择标签
    var labelSelect = xmSelect.render({
        el: '#labelIds',
        tips: '请选标签',
        autoRow: true,
        toolbar: {
            show: true,
            list: ['CLEAR']
        },
        //自定义属性
        prop: {
            name: 'labelName',
            value: 'id',
        },
        radio: false,
        layVerify: 'required',
        name: 'labelIds',
        data: [],
        size: 'small',
        filterable: true,
        paging: true,
        pageSize: 5,
        template: function ({item, sels, name, value}) {
            if (item.hasTimes) {
                return "<div class=\"xm-option   show-icon\"><div class=\"xm-option-content\"><span style='min-width: 100px'>" + name + "</span></div><input data-id='" + item.id + "' id=" + 'label_' + item.id + " oninput='stopPropagation(this)' placeholder=\"次数\" type=\"number\" value='" + (item.times ? item.times : '') + "' class=\"layui-input times\"></div>";
            } else {
                return "<div class=\"xm-option   show-icon\"><div class=\"xm-option-content\"><span style='min-width: 100px'>" + name + "</span></div></div>";
            }
        },
    });
    var labelAjax = new $ax(Changein.ctxPath + "/columnLabel/list")
    labelAjax.set("limit", 1000)
    let labelRes = labelAjax.start();
    labelSelect.update({
        data: labelRes.data
    })
    labelTimes = labelRes.data
    //------------图片上传---------------
    var upload = layui.upload;
    var filePath = new Array();
    upload.render({
        elem: '#imageUrl'
        , accept: 'file' //普通文件 images（图片）、file（所有文件）、video（视频）、audio（音频）
        , exts: 'jpg|jpeg|png' //只允许上传指定后缀的文件，一般结合 accept 参数类设定 jpg|png|gif|bmp|jpeg
        , url: Changein.ctxPath + '/file/uploadFile' //统一上传接口，不用改
        , data: {"moduleCode": "TEMPLATE", "moduleName": "文章"}   //模块名称和编号需要到开发管理-字典管理-文件上传模块类型中设置
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#imageUrlPreview').attr('src', result); //图片链接（base64）
                $('#imageUrlPreview').show()
            });
        }
        , done: function (res) {
            if (res.code == 200) {
                Changein.success("文件上传成功！" + res.data.src);
                filePath.push(res.data.src);
                $("#imageUrlInputId").val(res.data.src);
            } else {
                Changein.error("文件上传失败！" + res.data.message, 5000);
            }
        }
        , error: function () {
            Changein.error("上传文件失败！");
        }
    });

    //---------------------分类-----------------------------------
    var categoryAjax = new $ax(Changein.ctxPath + "/contentCategory/list")
    categoryAjax.set("limit", 1000)
    categoryAjax.set("associationType", 2)
    let categoryRes = categoryAjax.start();
    if (isResultOK(categoryRes)) {
        let categorySelect = $("select[name='categoryId']")
        categoryRes.data.forEach(function (item) {
            console.log(item)
            categorySelect.append(" <option value=\"" + item.id + "\"> " + item.assortName + "</option>")
        })
        form.render()
    } else {
        Changein.error("获取分类列表失败");
    }

    //---------------------来源--------------------------------------
    var sourceAjax = new $ax(Changein.ctxPath + "/sourceManage/allSourceList");
    let sourceRes = sourceAjax.start();
    if (isResultOK(sourceRes)) {
        let sourceSelect = $("select[name='originateId']");
        sourceRes.data.forEach(function (item) {
            sourceSelect.append(" <option value=\"" + item.id + "\"> " + item.sourceName + "</option>")
        })
        form.render();
    }

});
setInterval(function () {
    $(".times").click(function (event) {
        event.stopPropagation()
    })
}, 500)

function stopPropagation(obj) {
    let id = $(obj).attr("data-id");
    for (let i = 0; i < labelTimes.length; i++) {
        if (labelTimes[i].id == id) {
            labelTimes[i].times = obj.value
            break
        }
    }
}

$(function () {
    ue = UE.getEditor('editor', {
        enterTag: '',
        autoHeightEnabled: false,
        zIndex: 9,
        initialFrameHeight: 400
    });
    getAreaInfo(1, 1)
})

/**
 *
 * @param parentId 父级id
 * @param type 1，省级，2，市级，3，区级
 */
function getAreaInfo(parentId, type = 1) {
    layui.use(['ax', 'form'], function () {
        let form = layui.form;
        var $ax = layui.ax;
        var ajax = new $ax(Changein.ctxPath + "/area/list");
        ajax.set("limit", 1000);
        ajax.set("parentId", parentId);
        var result = ajax.start();
        if (isResultOK(result)) {
            let select
            if (type === 1) {
                select = $("select[name='provinceId']");
                select.html(" <option value=\"\">请选择省</option>")
                select.parents().next().find("select").html('<option value=\"\">请选择市</option>')
                select.parents().next().next().find("select").html('<option value=\"\">请选择县/区</option>')
            } else if (type === 2) {
                select = $("select[name='cityId']")
                select.html(" <option value=\"\">请选择市</option>")
                select.parents().next().find("select").html('<option value=\"\">请选择县/区</option>')
            } else {
                select = $("select[name='areaId']");
                select.html(" <option value=\"\">请选择县/区</option>")
            }
            result.data.forEach(function (item) {
                select.append(" <option value=\"" + item.id + "\"> " + item.name + "</option>")
            })
        } else {
            layer.msg("查找省市区失败", {icon: 5, anim: 6});
        }
        form.on('select()', function (data) {
            let lay_filter = $(data.elem).attr("lay-filter")
            if (data.value !== undefined && lay_filter === 'area-change-1') {
                getAreaInfo(data.value, 2)
            } else if (data.value !== undefined && lay_filter === 'area-change-2') {
                getAreaInfo(data.value, 3)
            }
        })
        form.render()
    })
}
